//
// Created by hay boy on 2022/7/6.
//

#ifndef ALGORITHMS_LABELCOMPONENTS_H
#define ALGORITHMS_LABELCOMPONENTS_H
#include "../queue/ArrayDeque.h"
#include "maze.h"
using namespace std;
void labelComponents(int ** pixel,int size);
void loopFunc(){
    int** pixel = new int*[10];
    int size = 8;
    for(int i = 0;i<10;i++){
        pixel[i] = new int[10];
        for(int j = 0;j<10;j++){
            pixel[i][j] = 0;
        }
    }
    pixel[1][3] = pixel[2][3] = pixel[2][4] = 1;
    pixel[3][5] = pixel[4][5]  = pixel[5][5] = 1;
    pixel[5][2] = pixel[5][7] = 1;
    pixel[6][1] = pixel[6][2] = pixel[6][3] = pixel[6][7] = 1;
    pixel[7][1] = pixel[7][2] = pixel[7][3] = pixel[7][6] = pixel[7][7] = 1;
    labelComponents(pixel,size);
    for(int i = 0;i<=size+1;i++){
        for(int j = 0;j<=size+1;j++){
            if(pixel[i][j]>1){
                cout<<i<<" "<<j<<" "<<pixel[i][j]<<endl;
            }
        }
    }
}
void labelComponents(int ** pixel,int size){
    position offset[4];
//    int size = 10;//size = 出口列标，为方形迷宫，行数=列数
    offset[0].row = 0;offset[0].col = 1;
    offset[1].row = 1;offset[1].col = 0;
    offset[2].row = 0;offset[2].col = -1;
    offset[3].row = -1;offset[3].col = 0;
    for(int i = 0;i<=size+1;i++){
        pixel[0][i] = pixel[size+1][i] = 0;
        pixel[i][0] = pixel[i][size+1] = 0;
    }
    int numberOfNbrs = 4;
    ArrayDeque<position> q;
    position here,nbr;
    int id = 1;
    for(int r = 1;r<=size;r++){
        for(int c = 1;c<=size;c++){
            if(pixel[r][c]==1){
                pixel[r][c] = ++id;
                here.row = r;
                here.col = c;
                while(true){
                    for(int i = 0;i<numberOfNbrs;i++){
                        nbr.row = here.row+offset[i].row;
                        nbr.col = here.col+offset[i].col;
                        if(pixel[nbr.row][nbr.col]==1){
                            pixel[nbr.row][nbr.col] = id;
                            q.push(nbr);
                        }
                    }
                    if(q.empty()){
                        break;
                    }
                    here = q.front();
                    q.pop();
                }
            }
        }
    }
}
#endif //ALGORITHMS_LABELCOMPONENTS_H
